// src/pages/Register.jsx
import React, { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { Form, Input, Button,  Upload, Cascader } from 'antd';
import { NavBar,Toast } from 'antd-mobile';  // 引入正确的 NavBar 
import { motion } from 'framer-motion';
import { useAuthStore } from '../store/authStore';
import { fadeIn } from '../styles/animations';
import { validateEmail, validateUsername,validatePassword } from '../utils/validation';
import { calculateConstellation } from '../utils/constellation';
import { cityData } from '../utils/cityData';
import { PlusOutlined } from '@ant-design/icons';



const Register = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const { register, loading, error, clearErrors } = useAuthStore();
  const [fileList, setFileList] = useState([]); // 存储头像
  const [cityVisible, setCityVisible] = useState(false);

  // 监听注册错误
  React.useEffect(() => {
    if (error) {
      Toast.show({
        content: error,
        position: 'center',
      });
      clearErrors();
    }
  }, [error, clearErrors]);

  // 头像上传前的处理
  const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      Toast.show({
        content: '只能上传图片文件！',
        position: 'center',
      });
      return false;
    }
    setFileList([file]); // 仅保留最新的头像
    return false; // 阻止默认上传行为
  };

  // 提交表单
  const onFinish = async (values) => {
    try {
      // 邮箱校验
      if (!validateEmail(values.email)) {
        Toast.show({
          content: '请输入有效的邮箱地址',
          position: 'center',
        });
        return;
      }
      
      // 密码校验
      if (!validatePassword(values.password)) {
        Toast.show({
          content: '密码至少需要8位字符',
          position: 'center',
        });
        return;
      }
      
      // 密码确认校验
      if (values.password !== values.passwordConfirm) {
        Toast.show({
          content: '两次输入的密码不一致',
          position: 'center',
        });
        return;
      }
      
      // 城市校验
      if (!values.city || values.city.length < 3) {
        Toast.show({
          content: '请选择完整的省市区信息',
          position: 'center',
        });
        return;
      }

      // 构造 FormData
      const formData = new FormData();
      formData.append('email', values.email);
      // formData.append('username', values.username);
      formData.append('password', values.password);
      formData.append('passwordConfirm', values.passwordConfirm);
      formData.append('city', values.city[1]); // 省市区
      formData.append('birth', values.birth);
      formData.append('constellation', calculateConstellation(values.birth));

      // 头像文件（可选）
      if (fileList.length > 0) {
        const file = fileList[0];
        const fileName = Math.random().toString(36).substring(2, 8) + '.png';
        formData.append('avatar', file, fileName);
      }

      await register(formData);
      Toast.show({
        content: '注册成功，请登录',
        position: 'center',
      });
      navigate('/login');
    } catch (err) {
      console.error('注册失败:', err);
    }
  };

  // 自定义样式
  const formItemStyle = {
    marginBottom: '0.15rem',
  };

  const labelStyle = {
    fontSize: '0.14rem',
    fontWeight: '500',
    color: '#333',
    marginBottom: '0.05rem',
  };

  const inputStyle = {
    fontSize: '0.14rem',
    height: '0.32rem',
    borderRadius: '0.04rem',
  };

  const cascaderStyle = {
    fontSize: '0.14rem',
    height: '0.32rem',
    borderRadius: '0.04rem',
  };

  const uploadStyle = {
    fontSize: '0.12rem',
  };

  return (
    <motion.div
      className="flex flex-col bg-white mobile-container"
      style={{
        height: '100vh',
        overflow: 'hidden',
      }}
      initial="hidden"
      animate="visible"
      exit="exit"
      variants={fadeIn}
    >

      <div 
        className="flex-grow flex flex-col justify-center mobile-scroll"
        style={{
          padding: '0.2rem',
          height: 'calc(100vh - 0.4rem)',
          overflowY: 'auto',
          overflowX: 'hidden',
        }}
      >
        <div className="w-full max-w-[2.8rem] mx-auto">
          <h9 className="text-center text-[0.28rem] font-bold text-gray-900">
            创建新账号
          </h9>
        </div>

        <div className="mt-[0.3rem] w-full max-w-[2.8rem] mx-auto">
          <div className="bg-white py-[0.3rem] px-[0.15rem]">
            <Form
              form={form}
              layout="vertical"
              onFinish={onFinish}
              size="small"
            >
              <Form.Item
                name="email"
                label="邮箱"
                rules={[{ required: true, message: '请输入邮箱' }]}
                style={formItemStyle}
                labelCol={{ style: labelStyle }}
              >
                <Input placeholder="请输入邮箱" style={inputStyle} />
              </Form.Item>

              {/* <Form.Item
                name="username"
                label="用户名"
                rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input placeholder="请输入用户名" />
              </Form.Item> */}

              <Form.Item
                name="password"
                label="密码"
                rules={[{ required: true, message: '请输入密码' }]}
                style={formItemStyle}
                labelCol={{ style: labelStyle }}
              >
                <Input placeholder="请输入密码" type="password" style={inputStyle} />
              </Form.Item>

              <Form.Item
                name="passwordConfirm"
                label="再次确认密码"
                rules={[{ required: true, message: '请输入密码' }]}
                style={formItemStyle}
                labelCol={{ style: labelStyle }}
              >
                <Input placeholder="再次确认密码" type="password" style={inputStyle} />
              </Form.Item>

              <Form.Item
                name="city"
                label="所在城市"
                rules={[{ required: true, message: '请选择省市区' }]}
                style={formItemStyle}
                labelCol={{ style: labelStyle }}
              >
                <Cascader 
                  options={cityData} 
                  placeholder="请选择省市区" 
                  changeOnSelect 
                  style={cascaderStyle}
                  dropdownStyle={{ fontSize: '0.12rem' }}
                />
              </Form.Item>

              <Form.Item
                name="birth"
                label="生日"
                rules={[{ required: true, message: '请输入生日' }]}
                style={formItemStyle}
                labelCol={{ style: labelStyle }}
              >
                <Input placeholder="请输入生日 (YYYY-MM-DD)" type="date" style={inputStyle} />
              </Form.Item>

              <Form.Item
                label="头像（可选）"
                style={formItemStyle}
                labelCol={{ style: labelStyle }}
              >
                <Upload
                  beforeUpload={beforeUpload}
                  listType="picture-card"
                  fileList={fileList.map(file => ({
                    uid: '-1',
                    name: file.name,
                    status: 'done',
                    url: URL.createObjectURL(file),
                  }))}
                  showUploadList={{ showPreviewIcon: true, showRemoveIcon: true }}
                  onRemove={() => setFileList([])}
                  style={uploadStyle}
                >
                  {fileList.length === 0 && (
                    <div style={{ fontSize: '0.12rem' }}>
                      <PlusOutlined />
                      <div style={{ marginTop: 4, fontSize: '0.12rem' }}>上传</div>
                    </div>
                  )}
                </Upload>
              </Form.Item>

              <Button 
                block 
                type="primary" 
                htmlType="submit" 
                loading={loading} 
                size="small" 
                className="mt-[0.2rem]" 
                style={{ 
                  fontSize: '0.16rem',
                  height: '0.36rem',
                  borderRadius: '0.04rem'
                }}
              >
                注册
              </Button>
            </Form>

            <div className="mt-[0.2rem] text-center">
              <Link to="/login" className="text-blue-500 hover:text-blue-700 text-[0.14rem]">
                已有账号？立即登录
              </Link>
            </div>
          </div>
        </div>
      </div>
    </motion.div>
  );
};

export default Register;
